package com.changgou.search.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.search.service.ESManagerService;
import com.changgou.search.service.SearchSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private ESManagerService esManagerService;
    @Autowired
    private SearchSevice searchSevice;

    /**
     * 添加索引
     * @return
     */
    @GetMapping("/createIndex")
    public Result createIndexAndMapping(){
        esManagerService.createIndexAndMapping();
        return new Result(true, StatusCode.OK,"添加索引成功");
    }

    /**
     * 导入搜索
     * @return
     */
    @GetMapping("/all")
    public Result importAll(){
        esManagerService.importAll();
        return new Result(true, StatusCode.OK,"添加搜索成功");
    }

    /**
     * 根据spuId添加对应的spu数据到搜索数据
     * @param skuid
     * @return
     */
    @GetMapping("/sku/{skuid}")
    public Result importAll(@PathVariable("skuid") String skuid){
        esManagerService.importData2ESBySpuId(skuid);
        return new Result(true, StatusCode.OK,"添加搜索成功");
    }

    /**
     * 根据搜索条件查询信息
     * @param searchMap
     * @return
     * @throws Exception
     */
    @GetMapping
    public Result<Map> search(@RequestParam Map<String,String> searchMap) throws Exception {
        //结果级格式转化，spec_中有+号
        handleSearchMap(searchMap);
        Map search = searchSevice.search(searchMap);
        return new Result<Map>(true,StatusCode.OK,"查询成功",search);
    }

    private void handleSearchMap(Map<String, String> searchMap) {
        Set<String> keys = searchMap.keySet();
        for (String key : keys) {
            if (key.startsWith("spec_")){
                searchMap.put(key,searchMap.get(key).replace(" ","+"));
            }
        }
    }

}
